const router = require('../../router');
const looksSame = require('looks-same');
const path = require('path');
const fs = require('fs');

/**
 * @openapi
 * /piper/compare/compareImage:
    post:
      summary: 比较图片
      tags: 
        - compareImage
      requestBody:
        required: true
        content: 
          application/json: 
            schema: 
              $ref: '#/components/schemas/compareImage'
      responses:  
        '200':
          content:
            application/json:
              example:
                code: "0"
                data: ""
                msg: "成功"
                success: true
 */
router.post('/compareImage', function (req, res) {
  console.log('compareImage', req.body);
  const {
    designName,
    codeName
  } = req.body;
  if (designName && codeName) {
    if (fs.existsSync(path.resolve(__dirname, `../../../../db/__temp__/${designName}`)) && fs.existsSync(path.resolve(__dirname, `../../../../db/__temp__/${codeName}`))) {
      const [, ...d] = designName.split('.'),
        [, ...c] = codeName.split('.');
      d.pop();
      c.pop();
      const dName = d.join(''),
        cName = c.join('');
      const compareName = `${Date.now()}.${dName}.${cName}.png`;
      looksSame.createDiff({
        reference: path.resolve(__dirname, `../../../../db/__temp__/${designName}`),
        current: path.resolve(__dirname, `../../../../db/__temp__/${codeName}`),
        diff: path.resolve(__dirname, `../../../../db/__temp__/${compareName}`),
        highlightColor: '#ff00ff', // color to highlight the differences
        strict: false, // strict comparsion
        tolerance: 2.5,
        antialiasingTolerance: 0,
        ignoreAntialiasing: true, // ignore antialising by default
        ignoreCaret: true // ignore caret by default
      }, function (error) {
        if (error) {
          return res.json({
            code: "-1",
            data: error,
            msg: '失败',
            success: false
          })
        } else {
          [codeName, designName].forEach(item => {
            fs.unlink(path.resolve(__dirname, `../../../../db/__temp__/${item}`), function (err) {
              if (err) {
                console.error(`删除文件 ${item} 失败，失败原因：${err}`)
              }
              console.log(`删除文件 ${item} 成功`)
            });
          })
          return res.json({
            code: "0",
            data: {
              compareName: compareName
            },
            msg: '成功',
            success: true
          })
        }
      });
    } else {
      return res.json({
        code: "-1",
        data: '所需对比图片不存在，请重新确认',
        msg: '失败',
        success: false
      })
    }
  } else {
    return res.json({
      code: "-1",
      data: '所需对比图片无法找到，请重新确认',
      msg: '失败',
      success: false
    })
  }
});

/**
 * @openapi
 * /piper/compare/downloadImage:
    post:
      summary: 下载比较图片
      tags: 
        - downloadImage
      requestBody:
        required: true
        content: 
          application/json: 
            schema: 
              $ref: '#/components/schemas/downloadImage'
      responses:  
        '200':
          content:
            application/json:
              example:
                code: "0"
                data: ""
                msg: "成功"
                success: true
 */
router.post('/downloadImage', function (req, res) {
  console.log('downloadImage', req.body);
  const {
    compareName
  } = req.body;
  if (compareName) {
    const f = fs.createReadStream(path.resolve(__dirname, `../../../../db/__temp__/${compareName}`));
    res.writeHead(200, {
      'Content-Type': 'application/force-download',
      'Content-Disposition': 'attachment; filename=' + compareName
    });   
    f.on('data', (data) => {
      res.write(data);
    }).on('end', () => {
      res.end();
      fs.unlink(path.resolve(__dirname, `../../../../db/__temp__/${compareName}`), function (err) {
        if (err) {
          console.error(`删除文件 ${compareName} 失败，失败原因：${err}`)
        }
        console.log(`删除文件 ${compareName} 成功`)
      });
    })
  } else {
    return res.json({
      code: "-1",
      data: '生成对比图片名称不正确，请重新确认',
      msg: '失败',
      success: false
    })
  }
});

module.exports = router;